package com.fr.report.script.function;

import com.fr.report.script.Function;
import com.fr.report.script.Function.Type;
import com.fr.report.script.NormalFunction;
import com.fr.report.script.Primitive;
import com.fr.report.script.core.FArray;
import com.fr.report.script.core.FunctionHelper;

public class AVERAGE extends NormalFunction
{
  public Object run(Object[] paramArrayOfObject)
  {
    double d = 0.0D;
    int i = 0;
    for (int j = 0; j < paramArrayOfObject.length; ++j)
    {
      if (paramArrayOfObject[j] == null)
        break label49:
      d += parseObject(paramArrayOfObject[j]);
      i += parseObjectCount(paramArrayOfObject[j]);
    }
    label49: return FunctionHelper.parsePrimitiveDouble(d / i);
  }

  private double parseObject(Object paramObject)
  {
    if (paramObject instanceof Number)
      return ((Number)paramObject).doubleValue();
    if (paramObject instanceof Boolean)
      return ((((Boolean)paramObject).booleanValue()) ? 1.0D : 0.0D);
    if (paramObject instanceof FArray)
    {
      FArray localFArray = (FArray)paramObject;
      double d = 0.0D;
      int i = 0;
      int j = localFArray.length();
      while (i < j)
      {
        d += parseObject(localFArray.elementAt(i));
        ++i;
      }
      return d;
    }
    if (paramObject != null)
      try
      {
        return Double.parseDouble(paramObject.toString());
      }
      catch (NumberFormatException localNumberFormatException)
      {
        return 0.0D;
      }
    return 0.0D;
  }

  private int parseObjectCount(Object paramObject)
  {
    if (paramObject instanceof FArray)
      return ((FArray)paramObject).length();
    if (!(paramObject instanceof Primitive))
      return 1;
    return 0;
  }

  public Function.Type getType()
  {
    return Function.MATH;
  }

  public String getCN()
  {
    return "AVERAGE(number1,number2,…): 返回指定数据的平均值。\nNumber1,number2…:用于计算平均值的参数。\n备注:\n    参数必须是数字，或是含有数字的名称，数组或引用。\n    如果数组或引用参数中含有文字，逻辑值，或空白单元格，这些值将被忽略；但是，单元格中的零值则参与计算。\n示例:\n如果A1:A6被命名为“ages”，分别等于10，23，14，24，33及25，则:\nAVERAGE(A1:A6)等于21.5。\nAVERAGE(ages)等于21.5。\n如果还有一个年龄为18的，求所有年龄的平均值为: AVERAGE(A1:A6,18)等于21。";
  }

  public String getEN()
  {
    return "AVERAGE(number1,number2,…): Returns the average (arithmetic mean) of the arguments.\nNumber1, number2, ...  are 1 to 30 numeric arguments for which you want the average.\n\nRemarks:\n1. The arguments must either be numbers or be names, arrays, or references that contain numbers. \n2. If an array or reference argument contains text, logical values, or empty cells, those values are ignored; however, cells with the value zero are included. \n\nExample:\n如果A1:A6被命名为“ages”，分别等于10，23，14，24，33及25，则:\nAVERAGE(A1:A6)等于21.5。\nAVERAGE(ages)等于21.5。\n如果还有一个年龄为18的，求所有年龄的平均值为: AVERAGE(A1:A6,18)等于21。";
  }
}